
<template>
  <div class="index-box" ref="index">
    <div class="backBox">
        <span class="back" @click="back"><i class="el-icon-back"></i>返回</span>
    </div>
    <div class="shop-box" v-loading="loading">
      <div class="d-flex">
        <div class="left">
          <el-form  :model="form" size="medium" ref="form"  class="form" :rules="rules" label-position="top">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span class="headerTitle">图文信息</span>
              </div>
              <div  class="text item">
                <el-form-item label="主图上传" prop="goodsImage">
                  <span slot="label">
                    主图上传 <span class="miniTips">（请上传图片规格为宽1500px、高1500px，大小不能超过10M的图片）</span>
                  </span>
                  <div class="d-flex">
                      <MyUpMoreImg  :imagePreview='form.goodsImage' size="750" imageLimit="1" text='上传主图' @change="imageChange($event,'goodsImage')"></MyUpMoreImg>
                  </div>

                </el-form-item>
                <el-form-item label="长图上传" prop="goodsWideImage">
                  <span slot="label">
                    长图上传 <span class="miniTips">（请上传图片规格为宽1360px、高580px，大小不能超过10M的图片）</span>
                  </span>
                  <div class="d-flex">
                      <MyUpMoreImg  :imagePreview='form.goodsWideImage' size="1360" imageSize="chang" imageLimit="1" text='上传长图' @change="imageChange($event,'goodsWideImage')"></MyUpMoreImg>
                  </div>

                </el-form-item>
                <el-form-item label="商品标题" prop="goodsName">
                  <span slot="label">
                    商品标题 <span class="miniTips">（标题不规范会引起商品下架，影响您的正常销售，请认真填写）</span>
                  </span>
                  <el-input v-model="form.goodsName" placeholder="请输入商品标题" maxlength="100" show-word-limit/>
                </el-form-item>
               <el-form-item label="商品类型" prop="goodsType">
                  <el-select  clearable v-model="form.goodsType" placeholder="请选择商品类型">
                    <el-option label="商家直销商品" value="1"></el-option>
                    <el-option label="活动特供商品" value="2"></el-option>
                    <el-option label="士多商品" value="3"></el-option>
                    <el-option label="霸王餐商品" value="4"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="商品规格" prop="rule">
                   <span slot="label" ><span class="red">*</span>商品规格<span class="miniTips">(注：规格需写明具体名称，如净含量、对、份、斤、克、毫升、袋、罐、件、箱等，最多添加3组规格（规格1*规格2*规格3 ≤450）)</span></span>
                  <div v-for="(item,index) in form.goodsSkuStockParamsList" class="rows">
                       <el-input v-model="item.specName" class="input" placeholder="请输入规格名称" />
                       <el-button class="table-btn" icon="el-icon-add" size="small"  @click="tagDeltRow(item,index)" v-if="index!='0'">删除当前行</el-button>
                  </div>
                  <div>
                    <el-button v-if="form.goodsType!='2'" class="table-btn" icon="el-icon-add" size="small" type="primary" plain  @click="tagAddRow('rule')" v-show="!(form.goodsSkuStockParamsList.length>6)">增加规格</el-button>
                  </div>
                </el-form-item>

                <el-form-item label="价格与库存" prop="goodsSkuStockParamsList">
                  <span slot="label" ><span class="red">*</span>价格与库存<span stye=""> <el-button style="margin-left:10px;" type="info" size="mini" @click="imgVisible=true">示例</el-button></span></span>
                  <el-table :data="form.goodsSkuStockParamsList" style="width: 100%"  border stripe >
                    <el-table-column prop="specification" label="规格">
                      <template #default="scope">
                         {{scope.row.specName}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="stockNum"  label="库存">
                      <template #header>
                        <span class="red">*</span>库存(件)
                      </template>
                      <template #default="scope">
                        <el-input v-model="scope.row.stockNum" class="input" placeholder="请输入库存" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="costPrice"  label="成本价(元)">
                      <template #header><span class="red">*</span>成本价(元)</template>
                      <template #default="scope">
                        <el-input v-model="scope.row.costPrice" class="input" placeholder="请输入成本价" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="originalPrice"  label="划线价(元)">
                      <template #header>
                        <span class="red">*</span>划线价(元)
                      </template>
                      <template #default="scope">
                        <el-input v-model="scope.row.originalPrice" class="input" placeholder="请输入原价" />
                      </template>
                    </el-table-column>
                    <!-- <el-table-column prop="salePrice"  label="平台售价(元)">
                      <template #header>
                        <span class="red">*</span>平台售价(元)
                      </template>
                      <template #default="scope">
                        <el-input v-model="scope.row.salePrice" class="input" placeholder="请输入平台售价" />
                      </template>
                    </el-table-column> -->
                    <!-- <el-table-column prop="unit"  label="单位">
                      <template #default="scope">
                        <el-input v-model="scope.row.unit" class="input" placeholder="请输入单位" />
                      </template>
                    </el-table-column> -->
                    <el-table-column prop="name"  label="操作">
                      <template #default="scope">
                        <el-button
                            size="medium"
                            type="text"
                            icon="el-icon-s-tools"
                            @click="setDetailList(scope.$index)"
                          >设置团购详情</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <p class="red" style="margin: 0px;">{{tips}}</p>
                </el-form-item>

                <el-form-item label="预览" prop="goodsDetails" v-if="form.goodsSkuStockParamsList[0].specName">
                  <div class="box">
                    <div class="boxTop">
                      <div class="botTopItem" :class="{'botTopItemActive':index==boxIndex}" v-for="(item,index) in form.goodsSkuStockParamsList" @click="boxIndex=index" >
                        {{item.specName}}
                      </div>
                    </div>
                    <div class="boxContent" v-for="(item,index) in form.goodsSkuStockParamsList" v-if="index==boxIndex">
                      <!-- <div class="boxContentTitle">
                        <span class="dian"></span>{{form.goodsName}}
                      </div> -->
                      <div class="" v-for="(item1,index1) in JSON.parse(item.specDetails)">
                        <div class="boxContentItem">
                          <div class="bciLeft d-flex align-center">
                            <span class="dian" v-if="item1.children.length"></span>{{item1.name}}
                          </div>
                          <div class="bciRight" v-if="!item1.children.length">
                            <span class="bciRNumber" v-if="item1.number">{{item1.number}}</span>
                            <span class="bciRNumber" v-if="item1.price">¥{{item1.price}}</span>
                            <span class="bciRNumber" v-if="item1.content">{{item1.content}}</span>
                          </div>
                        </div>
                        <div class="boxContentItemChild" style="padding-left:8px;border-bottom: 1px solid #ddd;" v-if="item1.children.length">
                          <div class="boxContentItem" v-for="(item2,index2) in item1.children">
                             <div class="bciLeft d-flex align-center">
                               {{item2.name}}
                             </div>
                             <div class="bciRight">
                               <span class="bciRNumber" v-if="item2.number">{{item2.number}}</span>
                               <span class="bciRNumber" v-if="item2.price">¥{{item2.price}}</span>
                               <span class="bciRNumber" v-if="item2.content">{{item2.content}}</span>
                             </div>
                           </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>

                <el-form-item label="商品使用规则说明" prop="useRule">
                  <QuillEditor  :value.sync="form.useRule" />
                </el-form-item>

                <el-form-item label="商品有效时间" prop="validTime">
                <el-date-picker v-model="form.validTime" type="daterange" align="right" unlink-panels range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions">
                  </el-date-picker>


                 <!-- <el-time-picker v-else  v-model="form.validTime" is-range range-separator="至"  start-placeholder="开始时间" end-placeholder="结束时间" format="HH-mm"  value-format="HH-mm">
                  </el-time-picker> -->
                </el-form-item>

                <el-form-item label="单次限购数量" prop="">
                  <el-input v-model="form.limitBuyNumber" placeholder="请输入单次限购数量" />
                </el-form-item>
                <el-form-item label="商品保障" prop="guarantee">
                  <el-input v-model="form.guarantee" placeholder="请输入商品保障" />
                </el-form-item>
                <!-- <el-form-item label="使用规则" prop="useRule">
                  <el-input v-model="form.useRule" placeholder="请输入使用规则" />
                </el-form-item> -->
                <el-form-item label="使用时间" prop="useTime">
                  <el-input v-model="form.useTime" placeholder="请输入使用时间" />
                </el-form-item>

              </div>
            </el-card>
          </el-form>
        </div>
      </div>
    </div>
    <div class="activeBox">
     <!-- <el-button type="info" @click="reset()">重置</el-button> -->
      <el-button type="primary" @click="submit('form')"  v-if="type!='detail'" v-loading="btnLoading">发布</el-button>
    </div>

   <el-dialog :title="detailTitle" :visible.sync="detailVisible" width="1080px" :close-on-click-modal="false">
      <el-table :data="specDetails" style="width: 100%;"  border stripe row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="name"  label="产品名称" >
          <template #default="scope">
            <el-input v-model="scope.row.name" class="input" placeholder="请输入产品名称" style="width: 80% !important;" />
          </template>
        </el-table-column>
        <el-table-column prop="name"  label="数量(份)" width="190">
          <template #default="scope">
            <el-input v-model="scope.row.number" class="input" placeholder="请输入数量" />
          </template>
        </el-table-column>
        <el-table-column prop="name"  label="市场价" width="190">
          <template #default="scope">
            <el-input v-model="scope.row.price" class="input" placeholder="请输入市场价" />
          </template>
        </el-table-column>
        <el-table-column prop="name"  label="内容" width="190">
          <template #default="scope">
            <el-input v-model="scope.row.content" class="input" maxlength="6" show-word-limit placeholder="请输入内容" />
          </template>
        </el-table-column>
        <el-table-column prop="name"  label="操作"  width="210">
          <template #default="scope">
              <el-button
                  size="medium"
                  type="text"
                  icon="el-icon-remove-outline"
                  @click="deltDetailRow(scope.row,scope.$index)"
                >删除当前行</el-button>
                <el-button
                    v-if="scope.row.children"
                    size="medium"
                    type="text"
                    icon="el-icon-folder-add"
                    @click="addDetailRowChild(scope.row,scope.$index)"
                  >新增子集
                  </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
          size="medium"
          type="text"
          icon="el-icon-circle-plus-outline"
          @click="addDetailRow()"
        >新增一列详情</el-button>

        <div slot="footer" class="dialog-footer">
           <el-button @click="detailVisible = false" size="small">取 消</el-button>
           <el-button type="primary" @click="handleSureDetail()" size="small" >确 定</el-button>
         </div>
    </el-dialog>

    <el-dialog title="示例" :visible.sync="imgVisible" width="600px" :close-on-click-modal="false">
      <div style="display: flex;justify-content: center;"><img src="https://qianzhi-mall.oss-cn-guangzhou.aliyuncs.com/dev/f421403359ba498d92e2652d60530097.png" alt="" style="margin: auto;" /></div>

     </el-dialog>

  </div>
</template>

<script>
  import { addGoods, getGoodsDetails,GoodsUpdate } from '@/api/getData';
  import option from '../../common/option.js';
  import common from "@/api/api";
  import { regionData,CodeToText } from 'element-china-area-data';
  import QuillEditor from '@/components/QuillEditor/quillEditor'

  export default {
    name:'shopDetails',
    components: { QuillEditor },
    inject: ['reload'],
    data() {
      let that = this
      return {
        loading:false,
        imgVisible:false,
        btnLoading:false,
        type:'',
        imagePreview: '',
        imageSource: '',
        tips:'',
        form:{
          goodsName:'',
          goodsImage:[],
          goodsWideImage:[],
          goodsType:'',
          goodsSkuStockParamsList:[{
            specName:'',//规格名称
            cargoNo:'',//货号
            costPrice:"",//成本价
            originalPrice:'',//原价
            salePrice:'',//平台售价
            stockNum:'',//库存数量
            unit:"",//单位
            specDetails:'[]',//规格详情JSON
          }],
          goodsDetails:'',
          limitBuyNumber:"",
          validTime:'',
          guarantee:'',//商品保障
          useRule:'',//使用规则
          useTime:'',//使用时间
        },

        rules: {
          goodsType: [{required: true, message: '请选择商品类型',trigger: 'blur'}],
          goodsImage: [{required: true, message: '请上传商品主图',trigger: 'blur'}],
          goodsWideImage: [{required: true, message: '请上传商品主图',trigger: 'blur'}],
          attachmentIds: [{required: true, message: '请上传商品图片',trigger: 'blur'}],
          goodsName: [{required: true, message: '请输入商品名称',trigger: 'blur'}],
          limitBuyNumber: [{required: true, message: '请输入单次限购数量',trigger: 'blur'}],
          validTime: [{required: true, message: '请选择商品有效时间',trigger: 'blur'}],
        },

        detailIndexStatus:'',
        specDetails:[],//规格详情
        detailVisible:false,
        detailTitle:'',

        boxIndex:0,
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.type = this.$route.query.type;
			this.goodsId = this.$route.query.goodsId;
			this.form.goodsId = this.$route.query.goodsId;

      if(this.goodsId){
        this.editDataInfo(this.goodsId);
      }
      // this.getSelectList('goods_type_key').then(res=>{
      //   this.sys_user_sex = res.data;
      // })
    },
    methods: {
      editDataInfo(){
        getGoodsDetails({goodsId:this.goodsId}).then((result) => {
          let goodsInfo = result.data.goodsInfo;
          let skuStockList = result.data.skuStockList;
          if (result.code == 200) {
            this.form.goodsName = goodsInfo.goodsName;
            this.form.goodsType = goodsInfo.goodsType+'';
            this.form.goodsImage = goodsInfo.goodsImage.split(',');
            this.form.goodsWideImage = goodsInfo.goodsWideImage?goodsInfo.goodsWideImage.split(','):[];
            this.form.goodsDetails = goodsInfo.goodsDetails;
            this.form.limitBuyNumber = goodsInfo.limitBuyNumber;
            this.form.validTime = goodsInfo.validTime?goodsInfo.validTime.split(','):[];

            this.form.goodsSkuStockParamsList = skuStockList;

            this.form.guarantee = goodsInfo.guarantee;
            this.form.useRule = goodsInfo.useRule;
            this.form.useTime = goodsInfo.useTime;
          } else {
            this.$message.error(result.message);
          }
        });
      },

      imageChange(path,name) {
        console.log(path);
        this.form[name] = path;
      },
      setDetailList(index){/* 弹框设置团购详情 */
        this.specDetails = JSON.parse(this.form.goodsSkuStockParamsList[`${index}`].specDetails);
        this.detailTitle = this.form.goodsSkuStockParamsList[`${index}`].specName+'团购详情';
        this.detailIndexStatus = index;
        this.detailVisible = true;
      },
      handleSureDetail(){
        for(let i=0;i<this.specDetails.length;i++){
          if(!this.specDetails[i].name){// || !this.specDetails[i].number || !this.specDetails[i].price
            this.$modal.msgError('请填写产品名称');
            return;
          }
        }
        this.form.goodsSkuStockParamsList[`${this.detailIndexStatus}`].specDetails = JSON.stringify(this.specDetails);
        this.detailVisible = false;
      },
      deltDetailRow(row,index){/* 删除团购详情当前列 */
       if (row.pid) {
            // 有父级元素，先找到父级元素，再从父级元素的children中删除
            this.deleteChildByid(this.specDetails, row.pid, row.id);
        }else{
           let fid = this.specDetails.findIndex((v) => {
              return v.id == row.id;
          });
          this.specDetails.splice(fid, 1);
        }

      },
      deleteChildByid(arr, pid, id) {
          let that = this;
          arr.forEach((v, i) => {
              if (v.id == pid) {
                  let item = v.children;
                  let idx = item.findIndex((p) => p.id === id);
                  item.splice(idx, 1);
              } else {
                  if (v.children && v.children.length > 0) {
                      that.deleteChildByid(v.children, pid, id);
                  }
              }
          });
      },
      addDetailRow(){/* 新增团购详情一列 */
        if(this.specDetails.length==10){
          this.$modal.msgError('最多添加十行');
          return;
        }
        let id =('000000' + Math.floor(Math.random() * 999999)).slice(-6);//随机数
        this.specDetails.push({id: id,name:'',number:'',price:'',content:'',children:[]});
      },
      addDetailRowChild(row,index){
        if(row.children.length==10){
          this.$modal.msgError('最多添加十行');
          return;
        }
        let id = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);//随机数
        let newObj = {
           id,//行id
           pid:row.id,//行的父级id
           name: "",
           number:'',
           price:'',
           content:''
        };
        row.children.push(newObj);
      },
      tagDeltVal(parentIndex,index,type){
          if(type=='params'){
             this.parameterList[parentIndex].child.splice(index,1);
          }else{
            this.ruleList[parentIndex].child.splice(index,1);
          }
          this.dataInfo();
      },
       tagAddRow(type,parentIndex){/* 添加规格 */
         if(this.form.goodsSkuStockParamsList.length=='6'){
           this.$modal.msgError('最多添加六行');
           return;
         }
         this.form.goodsSkuStockParamsList.push({
            specName:'',//规格名称
            cargoNo:'',//货号
            costPrice:"",//成本价
            originalPrice:'',//原价
            salePrice:'',//平台售价
            stockNum:'',//库存数量
            unit:"",//单位
            specDetails:'[]',//规格详情JSON
          })
       },
      tagDeltRow(index,type){/*删除当前行*/
        this.form.goodsSkuStockParamsList.splice(index,1);
      },
      submit(formName) {
        this.$refs[formName].validate(async(valid) => {
          if (valid) {
            for(let i=0;i<this.form.goodsSkuStockParamsList.length;i++){
              if(!this.form.goodsSkuStockParamsList[i].specName){
                this.tips = '请填写规格名称';
                return;
              }else if(!this.form.goodsSkuStockParamsList[i].stockNum){
                this.tips = '请填写库存';
                return;
              }else if(!this.form.goodsSkuStockParamsList[i].costPrice){
                this.tips = '请填写成本价';
                return;
              }else if(!this.form.goodsSkuStockParamsList[i].originalPrice){
                this.tips = '请填写原价';
                return;
              }
              // else if(!this.form.goodsSkuStockParamsList[i].salePrice){
              //   this.tips = '请填写平台售价';
              //   return;
              // }
            }
            this.tips = '';
            this.btnLoading = true;
            let data = JSON.parse(JSON.stringify(this.form))
            data.goodsImage = data.goodsImage.join(',');
            data.goodsWideImage = data.goodsWideImage.join(',');
            if(data.validTime.length){
              data.validTime = data.validTime.join(',');
            }

            let result;
            if(this.form.goodsId){
              result = await GoodsUpdate(data);
            }else{
              result = await addGoods(data);
            }
            if (result.code == 200) {
              this.$message.success(result.msg);

            } else {
              this.$message.error(result.message);
            }
            this.btnLoading = false;
            this.$router.go(-1);
          }
        })
      },
      back(){
        this.$router.push({path:'/shop/shopIssue'});
      },
    }
  }
</script>

<style scoped lang="scss">
  .box{
     width:380px;
     border:1px solid #999;
     border-radius: 10px;
     padding:15px;
  }
  .boxTop .botTopItem.botTopItemActive{
    border: 1px solid #FC5173;
    background: rgba(252,81,115,0.05);
  }
  .boxTop{
    display: flex;
  }
  .boxTop .botTopItem{
   padding:0 20px;

    height: 100rpx;
    background: #F1F1F1;
    border-radius: 10px;
    color:#666;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    margin-right:20px;
  }
  .boxContentTitle{
    display: flex;
    color:#333;
    align-items: center;
  }
  .dian{
    height: 4px;
    width: 4px;
    border-radius: 50%;
    background-color:#333;
    font-size: 20px;
    margin-right:5px;
  }
  .boxContentItem{
    display: flex;
    width: 100%;
    justify-content: space-between;
       padding-left:10px;
  }
  .bciRNumber{
    margin-right:10px;
  }



  .tableBox /deep/ .el-form-item__content{
    width:100%;
    overflow-x: auto;
  }
  .shop-box /deep/ .el-form-item__label{
    padding:0px;
  }
  .miniTips{
    font-size: 12px;
    color:#CCC4CC;
    padding-left:4px;
  }
  .box-card{
    margin-bottom: 15px;
  }
  .headerTitle{
    font-size: 16px;
    font-weight: bold;
  }
	.index-box /deep/ .ql-editor{
		min-height: 300px;
	}
	.boxs /deep/ .el-radio-group{
  	display: flex;
  	flex-wrap: wrap;
  }
  .boxs /deep/ .el-radio-group .el-radio{
  	width:100%;
  	margin-bottom: 10px;
  }
  .activeBox{
    display:flex;
    justify-content:center;
  }
  .upGoodBox{
    height:100px;
    display:flex;
    align-items:center;
    justify-content: center;
    background: rgba(158, 187, 169, 0.15);
    color:#3A7654;
    margin-bottom:20px;
  }
  .shop-box{
    margin: 0 auto;
    .left{
      width:80%;
      padding:0 10px;
      margin: auto;
    }
    // .right{
    //   width:35%;
    //   padding:0 10px;
    // }
  }
  .el-checkbox-group{
    display: flex;
    flex-direction: column;
  }
  .jobNumber{
    text-align:center;
    color:#606266;
    margin:0;
  }
  .index-box /deep/ .el-checkbox{
    margin-bottom:15px;
  }
  .auditBox{
    padding: 20px 50px;
    background: rgba(158, 187, 169, 0.15);
    margin-bottom:20px;
    .steps{
      max-width:500px;
      margin:0 auto;
    }
  }
  .goodSet{
    padding: 50px 50px 30px 50px;
    background: rgba(158, 187, 169, 0.15);
    margin-bottom:20px;
    color:#606266;
    .title{
      text-align: center;
      font-size:18px;
      margin-bottom:10px;
    }
  }
  .el-icon-edit-outline{
    color: rgb(97, 153, 122);
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
  }
  /*.myQuillEditor{
    height:250px;
  }*/
  table {
    width: 100%;
  }

  th {
    height: 50px;
    text-align: left;
    border-bottom: 1px solid #EBEEF5!important;
    color:#909399;
    padding:0 5px;

  }
  table{
    border: 1px solid #EBEEF5;
  }
  td, th{
    border:none;
    white-space: nowrap;
    min-width: 80px;
  }
  td{padding:5px}
  .index-box{
    height:100%;
    overflow-y: auto;
  }
  .shop-box{
    margin: 0 auto;
    .left{
      width:90%;
      padding:0 10px;
    }
    // .right{
    //   width:35%;
    //   padding:0 10px;
    // }
  }
  .rows>div,.rows>button{
    margin-bottom: 5px;
  }
  .input{
    width:150px;
    margin-right:10px;
  }
  .form{
    padding:20px 0;
  }
   .form /deep/ .avatar-uploader .el-upload-list__item{display: none;}
  .avatar-uploader{
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      height:100px;
      width:100px;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
        height: 30px;
        line-height: 30px;
        margin-top: 15px;
        margin-bottom: 10px;
        font-size: 28px;
        color: #8c939d;
    }
    .d-flex /deep/ .el-upload{
      display: block;
    }
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
    .text{
      margin: 0px;
      color: #8c939d;
    }
    .upImg /deep/ .el-upload--text{
      height:100%
    }
    .activeBox{
      display: flex;
      justify-content: center;
    }
    .el-upload-list--picture-card .el-upload-list__item{
        width:100px;
        height:100px;
    }
</style>
